﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using Lyh.XianGuo.Reader.Common;
using Lyh.XianGuo.Reader.Model;

namespace Lyh.XianGuo.Reader.Exchange
{
    public class Analyze
    {
        private readonly string bookUrl = string.Empty;
        private const string Domain = "http://xianguo.com";
        public delegate void PageDownloadedHander(int pageIndex);

        public event PageDownloadedHander OnPageDownloaded;

        public Analyze(string url)
        {
            bookUrl = url;
        }

        public Book GetBook()
        {
            var book = new Book();

            return book;
        }

        public Book ExtractBookInfo()
        {
            var httpClient = new HttpClient();
            var parameter = new HttpParameter()
            {
                Url = bookUrl
            };
            var html = httpClient.Request(parameter).Replace("\r", "").Replace("\n", "").Replace("\t", "");

            var volumes = Regex.Matches(html, "<div class=\"b-volume\">(?<volume>.*?)</ul></div>");

            var pageIndex = 0;
            var book = new Book();
            var chapters = new List<Chapter>();
            for (var j = 0; j < volumes.Count; j++)
            {
                var pageContent = Regex.Matches(volumes[j].Groups["volume"].Value, "<li>(?<content>.*?)</li>");
                var pages = new List<Page>();
                for (var i = 0; i < pageContent.Count; i++)
                {
                    pageIndex++;
                    var pageTitle = Regex.Match(pageContent[i].Groups["content"].Value, "title=\"(?<title>.*?)\"");
                    var pageHref = Regex.Match(pageContent[i].Groups["content"].Value, "href=\"(?<href>.*?)\"");
                    var page = new Page()
                    {
                        Id = pageIndex,
                        Name = pageTitle.Groups["title"].Value,
                        Href = pageHref.Groups["href"].Value
                    };
                    pages.Add(page);
                }

                var volumeTitle = Regex.Match(volumes[j].Groups["volume"].Value,
                    "<div class=\"b-volume-title clearfix\"><span class=\"fl\">(?<title>.*?)</span></div>");
                var chapter = new Chapter()
                {
                    Id = j + 1,
                    Name = volumeTitle.Groups["title"].Value,
                    Pages = pages
                };
                chapters.Add(chapter);
            }
            var bookName = Regex.Match(html, "《(?<name>.*?)》");
            book.Name = bookName.Groups["name"].Value;
            book.Chapters = chapters;
            book.Count = pageIndex;
            book.Id = bookUrl.Substring(bookUrl.LastIndexOf('/') + 1).Trim();
            return book;
        }

        public void SaveBookInfo(Book book)
        {
            var folder = string.Format("{0}\\Books\\{1}", Environment.CurrentDirectory, book.Id);
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
            var file = string.Format("{0}\\{1}.json", folder, book.Id);
            var json = book.ToJson();
            File.WriteAllText(file, json, Encoding.UTF8);
        }

        public void ExtractBookContent(Book book)
        {
            foreach (var chapter in book.Chapters)
            {
                foreach (var page in chapter.Pages)
                {
                    var url = string.Format("{0}{1}", Domain, page.Href);
                    var httpClient = new HttpClient();
                    var parameter = new HttpParameter()
                    {
                        Url = url
                    };
                    var html = httpClient.Request(parameter);
                    var content = Regex.Match(html, "<div class=\"content\">(?<content>.*?)</div>\n    <a", RegexOptions.Singleline);
                    var path = string.Format("{0}/Books/{1}/{2}.html", Environment.CurrentDirectory, book.Id, page.Id);
                    var text = string.Format("<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"../reader.css\"></head><body><div class=\"rd-page\"><div class=\"content\">{0}</div></div></body></html>", content.Groups["content"].Value);
                    File.WriteAllText(path, text, Encoding.UTF8);
                    if (OnPageDownloaded != null) OnPageDownloaded(page.Id);
                }
            }
        }
    }
}
